/**
 * 用户个人信息
 *
 * Created by snowingsea on 2020/01/30.
 */
const middleware = require('./middleware');
const users = require('./../models/users');
const encrypt = require('./../models/encrypt');
const publisher = require('./../models/redis/publisher');
const PhoenixError = require('./../models/phoenix-error');

/**
 * 获取用户信息
 * @param req
 * @param res
 * @param next
 */
function getMyInfo(req, res, next) { // eslint-disable-line no-unused-vars
  users.getSummaryJson(req.$me)
    .then((user) => {
      res.json(user);
    })
    .catch((err) => {
      next(new PhoenixError(err));
    });
}

/**
 * 更新用户信息
 * @param req
 * @param res
 * @param next
 */
function updateMyInfo(req, res, next) {
  const userId = req.$me._id; // eslint-disable-line no-underscore-dangle
  const { nickname, lang } = req.query;
  users.updateUser(userId, { nickname, lang })
    .then(() => users.getUser(userId))
    .then((user) => {
      res.json(users.getJson(user));
    })
    .catch((err) => {
      next(new PhoenixError(err));
    });
}

/**
 * 修改密码
 * @param req
 * @param res
 * @param next
 */
function changeMyPassword(req, res, next) {
  const userId = req.$me._id; // eslint-disable-line no-underscore-dangle
  const { oldPassword, newPassword } = req.body;
  encrypt.compare(oldPassword.toLowerCase(), req.$me.salt, req.$me.password)
    .then((isPasswordMatch) => {
      if (!isPasswordMatch) {
        return Promise.reject(new PhoenixError('invalid request', 'The old password do not match'));
      }
      return users.updateUser(userId, { password: newPassword, state: users.statusKind.offline });
    })
    .then(() => {
      // 用户下线
      publisher.publishLogoutMessage(userId);
      res.status(200).json();
    })
    .catch((err) => {
      next(new PhoenixError(err));
    });
}

/**
 * Export model definition object.
 */
module.exports = (app, prefix) => {
  const meURL = `${prefix}/me.json`;
  const passwordURL = `${prefix}/me/password.json`;

  // 获取用户个人信息
  app.get(meURL, middleware.license.detectSystemTimeTampering);
  app.get(meURL, middleware.user.requireTokenUnexpired);
  app.get(meURL, middleware.user.requireAvailable);
  app.get(meURL, getMyInfo);

  // 编辑个人信息
  app.put(meURL, middleware.user.requireTokenUnexpired);
  app.put(meURL, middleware.user.requireAvailable);
  app.put(meURL, updateMyInfo);

  // 修改密码
  app.put(passwordURL, middleware.user.requireTokenUnexpired);
  app.put(passwordURL, middleware.user.requireAvailable);
  app.put(passwordURL, middleware.user.requirePasswordDifferent);
  app.put(passwordURL, changeMyPassword);
};
